<?php

/**
 * 微信投票 Service
 * 
 * @path    Apps/Common/Service/WxEventVoteService.class.php
 * @author  Zix 
 * @version v1.0 , 2015-09-11
 */

namespace Common\Service;

class WxEventVoteService {

  private static $instance;

  const EVENT_BASE_URL = 'Wechat/Vote/index';

  public static function instance() {
    if (self::$instance == null) {
      $instance = new WxEventVoteService();
    }

    return $instance;
  }

  function get_default_row() {
    return array(
      'keyword' => '',
      'icon' => '',
      'bg_img' => '',
      'name' => '',
      'rule' => '',
      'share_title' => '',
      'share_desc' => '',
      'start_time' => '',
      'end_time' => '',
      'daily_times' => '0',
      'total_active_user' => '0',
    );
  }

  function get_by_id($id) {
    $WxEventVote = M('WxEventVote');
    $data = $WxEventVote->find($id);
    return $data ? $data : array();
  }
  
  function get_by_keyword( $wx_id , $keyword ) {
    $WxEventVote = M('WxEventVote');
    
    $today = date('Y-m-d') ;
    $where = array(
      'wx_id' => $wx_id ,
      'keyword' => $keyword ,
      '_string' => "date_format(start_time , '%Y-%m-%d') <= '$today' and date_format(end_time , '%Y-%m-%d') >= '$today'",
    );
    
    $data = $WxEventVote->where($where)->select();
    $ret = $this->_fix_for_api($data);
    return $ret ;
  }
  
  function _fix_for_api( $arr ) {
    $ret = array();
    foreach ( $arr as $row ) {
      $ret[] = array(
     		'Title'=>$row['name'],
     		'Description'=>$row['share_desc'],
     		'PicUrl'=> U($row['icon'] , '' , TRUE , TRUE ),
     		'Url' => $row['url']
      );
    }
    return $ret;
  }
  

  function get_by_cond($config) {
    $default = array(
      'keyword' => '',
      'page' => 1,
      'page_size' => 6,
      'status' => '',
      'wx_id' => '',
      'count' => FALSE,
      'order' => 'DESC',
      'sort' => 'id',
    );

    $config = extend($config, $default);

    $WxEventVote = M('WxEventVote');

    $where = array();

    if ( !empty( $config['keyword'] ) ) {
      $k = $config['keyword'];
      $where['_string'] = " nickname = '$k' or code = '$k' ";
    }
    
    if (!empty($config['status'])) {
      $where['status'] = $config['status'];
    }
    
    if (!empty($config['wx_id'])) {
      $where['wx_id'] = $config['wx_id'];
    }

    if ($config['count']) {
      return $WxEventVote->where($where)->count();
    } else {
      $order = $config['sort'] . ' ' . $config['order'];
      $limit = ($config['page'] - 1 ) * $config['page_size'] . ' , ' . $config['page_size'];
      $data = $WxEventVote
          ->where($where)
          ->limit($limit)->order($order)->select();
      //echo $WxEventVote->_sql();
      return $data ? $data : array();
    }
  }

  function create($data) {
    $WxEventVote = M('WxEventVote');

    $ret = $WxEventVote->add($data);
    if ($ret === FALSE) {
      return ajax_arr('添加失败', FALSE);
    } else {
      $this->_after_create( $data['mer_id'] , $data['wx_id'] , $ret);
      return ajax_arr('添加成功', TRUE, array(
        'id' => $ret
      ));
    }
  }
  
  function _after_create( $mer_id , $wx_id , $event_id ) {
    $data['url'] = $this->get_wx_oauth_url($mer_id , $wx_id, $event_id);
    $WxEventVote = M('WxEventVote');
    $WxEventVote->where('id = %d' , $event_id )->save( $data );
  }
  
  //取活动真实 url
  function get_event_url( $mer_id , $wx_id , $event_id ) {    
    $query = array(
      'mer_id' => $mer_id ,
      'wx_id' => $wx_id ,
      'envent_id' => $event_id ,
    );
    
    return U( self::EVENT_BASE_URL , '' , TRUE , TRUE ) . '?' . http_build_query($query);
  }

  //微信 oauth url
  function get_wx_oauth_url( $mer_id , $wx_id , $event_id ) {
    $url = $this->get_event_url($mer_id, $wx_id, $event_id);
    
    $wechatsdk = new WechatSdkService( $mer_id , $wx_id );
    return $wechatsdk->getOauthRedirect($url); 
  }
    
  function update($id, $data) {
    $WxEventVote = M('WxEventVote');

    $ret = $WxEventVote->where("id = %d", $id)->save($data);
    if ($ret === FALSE) {
      return ajax_arr('编辑失败', FALSE);
    } else {
      return ajax_arr('编辑成功', TRUE);
    }
  }

  function delete($ids) {
    $WxEventVote = M('WxEventVote');
    $ret = $WxEventVote->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }
  
  function do_vote( $event_id ,  $user_id , $player_id ) {
    //取活动内容
    $event_data = $this->get_by_id($event_id);
    
    if ( empty( $event_data ) ) {
      return ajax_arr('活动不存在');
    }
    
    if( strtotime( $event_data['end_time'] ) < time()  ) {
      return ajax_arr('活动已经结束');
    }

    //检查player_id 状态
    $WxEventVotePlayer = WxEventVotePlayerService::instance();
    $player_data = $WxEventVotePlayer->get_by_id($player_id);
    
    if ( $player_data['status'] != 1 ) {
      return ajax_arr('用户状态不正确');
    }
   
    $WxEventVoteUser = WxEventVoteUserService::instance();
    
    //今天是否已经投过该人了
    $today_vote = $WxEventVoteUser->get_by_user_player_today($user_id, $player_id);
    if ( !empty( $today_vote ) ) {
      return ajax_arr('今天你已为TA投过了');
    }
    
    //如果限制了 就 检查 是否投票超过限制
    $count_daily = $WxEventVoteUser->count_daily_by_user($user_id);
    if ( $event_data['daily_times'] > 0 ) {
      if ( $count_daily >= $event_data['daily_times'] ) {
        return ajax_arr('您今天已经投了 '. $count_daily.' 票了，请明天再来吧');
      }
    }
    
    //开始投票
    $new_data = array(
      'event_id' => $event_id ,
      'user_id' => $user_id ,
      'player_id' => $player_id ,
      'ipaddress' => get_client_ip(0, TRUE),
    );
    $ret = $WxEventVoteUser->create($new_data);
    
    if ( !$ret['status'] ) {
      return ajax_arr('投票失败，请稍后再试');
    }
    
    $WxEventVotePlayer->add_vote($player_id); 
    
    $vote_left = $event_data['daily_times'] - $count_daily - 1 ;
    $text = '投票成功，您今天还可以投 ' . $vote_left . ' 票' ;
    return ajax_arr($text , TRUE );
  }

}
